<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace app\api\controller\v4;

use app\api\controller\v2\Auth;
use app\common\model\Recode;
use think\Cache;
use think\Db;
use app\common\model\MapCollect;
use think\Log;

/**
 * @title 我的收藏相关接口
 * @desc 查看文章详情<br/>按页码获取文章列表，每页十条<br/>
 * @url /api/v2/article
 * @version 2.0.0
 * Class Article
 * @package app\api\controller\v2
 */
class Collect extends Auth
{
    /**
     * 地图收藏列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $map = [];

        $map['page'] = input('get.page/d', 1);

        $map['rid'] = input('get.rid', 0);

        $map['uid'] = $this->user['id'];

        $MapCollectModel = new MapCollect();

        if (!$map['rid'])
        {
            if ($this->user['rid'])
            {
                $map['rid'] = $this->user['rid'];
            }
        }


        // 获取当前用户的档案id
        try
        {
            if ($map['rid'])
            {
                $recode = (new Recode())->getRecode(['id' => $map['rid']]);
                if (!$recode || $recode['uid'] != $this->user['id'])
                {
                    return show(config('code.error'), '档案不存在');
                }
                $map['is_self'] = $recode['isself'] ? 1 : 0;
            } else
            {
                $map['is_self'] = 0;
            }
            $result = $MapCollectModel->collect_rid($map);
        }
        catch (\Exception $e)
        {
            $result = [];
        }

        return show(config('code.success'), '加载成功', $result);
    }


    /**
     * 保存收藏
     */
    public function save()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param = request()->only(['name', 'des', 'longitude', 'latitude', 'type', 'rid']);

        $validate = validate('Collect');

        if (!$validate->scene('save')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $recode = (new Recode())->getRecode(['id' => $param['rid']]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        $map = [
            'longitude' => (float)$param['longitude'],
            'latitude' => (float)$param['latitude']
        ];

        $where = ['longitude' => $map['longitude'], 'latitude' => $map['latitude']];

        try
        {
            $mids = Db::table('app_map')->field('id')->where($where)->findOrFail();
            $mid = $mids['id'];
        }
        catch (\Exception $e)
        {
            $mid = false;
        }

        if ($mid === false)
        {
            try
            {

                $mid = Db::table('app_map')->insertGetId($map);

            }
            catch (\Exception $e)
            {
                Log::write('收藏地点经纬度入库失败' . $e->getMessage() . var_export(request()->param(), true), 'map_collect_error', true);

                return show(config('code.error'), '该地点已收藏');
            }
        }


        $collect = [
            'uid' => $this->user['id'],
            'rid' => (int)$param['rid'],
            'mid' => (int)$mid,
            'name' => $param['name'],
            'des' => $param['des'],
            'type' => (int)$param['type'],
            'create_time' => time()
        ];

        try
        {

            $id = Db::table('wechat_backup_07_18_14_43_00.app_map_collect')->insertGetId($collect);

            //删除列表的缓存，那么到收藏页面重新获取，这里为了保证数据的及时性
            Cache::rm('map_collect_list_ids1_' . $param['rid']);
            $map_collect_rids = Cache::get('map_collect_rids1_' . $this->user['id']);
            if (!$start = strpos($map_collect_rids, (string)$param['rid']))
            {//如果当前收藏地点的档案rid不在缓存列表，那么就删除
                Cache::rm('map_collect_rids1_' . $this->user['id']);
            }

        }
        catch (\Exception $e)
        {
            Log::write('收藏地点入库失败：' . $e->getMessage() . var_export(request()->param(), true), 'map_collect_error', true);

            return show(config('code.error'), '操作失败，请稍后重试！');
        }

        return show(config('code.success'), '收藏成功', $id);
    }


    /**
     * 更新收藏
     */
    public function update()
    {
        if (!request()->isPut())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $id = input('param.id/d');

        $name = input('param.name/s');

        $info = [
            'remark' => $name,
            'id' => $id
        ];

        $validate = validate('Collect');

        if (!$validate->scene('update')->check($info))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $where = ['id' => $id, 'uid' => $this->user['id']];

        try
        {

            Db::table('app_map_collect')->where($where)->update(['name' => $name]);
            Cache::rm(MapCollect::REDIS_KEY_MAP_COLLECT_DETAIL . $id);

        }
        catch (\Exception $e)
        {
            Log::write('更新地点收藏失败：' . $e->getMessage() . var_export(request()->param(), true), 'map_collect_error', true);

            return show(config('code.error'), '操作失败');
        }

        return show(config('code.success'), '操作成功', []);
    }

    /**
     * 删除收藏
     */
    public function del()
    {
        if (!request()->isDelete())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $ids = explode(',', input('param.ids'));

        $type = input('param.type');

        $info = [
            'id' => input('param.ids'),
            'sort' => $type
        ];

        $validate = validate('Collect');

        if (!$validate->scene('del')->check($info))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        if ($type == 1)
        {
            //取消文章收藏
            try
            {
                Db::table('wechatadmin.system_article_collect')
                    ->where('aid', 'in', $ids)
                    ->where('ucid', $this->user['uc_id'])->delete();
                Db::table('wechatadmin.system_article')->where('id', 'in', $ids)->setDec('collect');

                //删除用户所有收藏文章id的缓存
                Cache::rm('article_collect_' . $this->user['id']);
                //删除用户所有收藏文章time的缓存
                Cache::rm('article_collect_time_' . $this->user['id']);


            }
            catch (\Exception $e)
            {

                Log::write('取消文章收藏失败' . $e->getMessage() . var_export(request()->param(), true), 'map_collect_error', true);

                return show(config('code.error'), '操作失败,请重试');

            }
        } elseif ($type == 2)
        {
            //取消地理收藏
            try
            {

                Db::table('app_map_collect')->where('id', 'in', $ids)->where('uid', $this->user['id'])->delete();
                //由于没有传rid，所以把用户下所有的rids的ids循环过滤删除
                $rids = Cache::get('map_collect_rids1_' . $this->user['id']);
                $rids = explode(',', $rids);
                array_shift($rids);//去除数组第一个元素
                if ($rids)
                {
                    foreach ($rids as $rid)
                    {
                        Cache::rm('map_collect_list_ids1_' . $rid);
                    }
                }
                Cache::rm('map_collect_rids1_' . $this->user['id']);


            }
            catch (\Exception $e)
            {
                Log::write('取消收藏失败：' . $e->getMessage(), 'good_error', true);
                return show(config('code.error'), '删除收藏失败');
            }

        } elseif ($type == 3)
        {
            // 取消文章点赞
            try
            {
                Db::table('wechatadmin.system_article_good')->where('aid', 'in', $ids)->where('ucid', $this->user['uc_id'])->delete();
                Db::table('wechatadmin.system_article')->whereIn('id', $ids)->setDec('good');

                //删除用户所有点赞文章id的缓存
                Cache::rm('article_good_' . $this->user['id']);
                //删除用户所有点赞文章time的缓存
                Cache::rm('article_good_time_' . $this->user['id']);
            }
            catch (Exception $e)
            {
                Log::write('取消点赞失败：' . $e->getMessage(), 'good_error', true);
                return show(config('code.error'), '删除文章点赞失败');
            }
        }
        return show(config('code.success'), '删除成功');
    }

}
